package cn.ycl.auth.biz.usercenter.service.impl;

import cn.hutool.json.JSONUtil;
import cn.ycl.auth.biz.usercenter.dao.UserDao;
import cn.ycl.auth.biz.usercenter.entity.RegisterParam;
import cn.ycl.auth.biz.usercenter.entity.User;
import cn.ycl.auth.biz.usercenter.service.LoginService;
import cn.ycl.auth.biz.usercenter.service.UserService;
import cn.ycl.auth.utils.TokenUtil;
import cn.ycl.constans.Result;
import cn.ycl.entity.LoginParam;
import cn.ycl.entity.UserInfoVO;
import cn.ycl.utils.IPUtil;
import cn.ycl.utils.RedisUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author YuanChangLiang
 * @Date 2020/11/10 20:58
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private UserService userService;
    @Resource
    private UserDao userDao;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 登录
     *
     * @param loginParam 登录类
     * @return 返回类
     */
    @Override
    public Result loginQuery(LoginParam loginParam, HttpServletRequest request) {
        //查询是否存在登录用户
        User user = userService.login(loginParam);
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }
        user.setLoginDate(new Date());
        user.setLoginIp(IPUtil.getIpAddress(request));
        String token = TokenUtil.createToken();
        //构建用户信息
        userDao.update(user);
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        userInfoVO.setToken(token);
        String s = JSONUtil.toJsonStr(userInfoVO);
        boolean set = redisUtil.set(token, s, 7200L);
        return Result.ok(userInfoVO);
    }


    /**
     * 注册
     *
     * @param registerParam 注册类
     * @return 返回类
     */
    @Override
    public Result register(RegisterParam registerParam) {
        if (registerParam.getUserName() != null && registerParam.getPassword() != null) {
            User user = new User();
            user.setUserName(registerParam.getUserName());
            List<User> users = userService.queryByUser(user);
            if (users.size() != 0) {
                return Result.fail("该用户名已存在");
            }
            user.setPassword(registerParam.getPassword());
            userService.insert(user);
            return Result.ok();
        }
        return Result.fail("注册失败，注册参数不全");
    }

}
